﻿using System.Text;
using Serilog.Core;
using Serilog.Events;

namespace Common.Serilog;

public class AppSourceContextEnricher : ILogEventEnricher
{
    public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
    {
        if (!logEvent.Properties.TryGetValue(Constants.SourceContextPropertyName, out LogEventPropertyValue? p)) return;
        var s = p.ToString();
        var arr = s.Replace("\"", "").Split(".");
        var src = new StringBuilder();
        var newSourceContext = new StringWriter(src);
        if (arr.Length > 1)
        {
            for (var i = 0; i < arr.Length; i++)
            {
                var cur = arr[i];
                if (i < arr.Length - 1)
                {
                    newSourceContext.Write(FirstLetter(cur));
                    newSourceContext.Write(".");
                }
                else
                {
                    newSourceContext.Write(cur);
                }
            }
        }
        else
        {
            newSourceContext.Write(string.Join('.', arr));
        }
        newSourceContext.Flush();
        var enSourceContext = propertyFactory.CreateProperty("EnSourceContext", src.ToString());
        logEvent.AddPropertyIfAbsent(enSourceContext);
    }

    private static string FirstLetter(string s)
    {
        return string.IsNullOrWhiteSpace(s) ? s : s.ToCharArray()[0].ToString().ToLower();
    }
}